<template>
  <a-menu
    mode="inline"
    theme="dark"
    :inline-collapsed="collapsed"
    v-model:selectedKeys="selectedKeys"
    v-model:openKeys="openKeys"
  >
    <menu-item v-for="item in menuList" :item="item" />
  </a-menu>
</template>

<script>
  import { reactive, toRefs, watch, getCurrentInstance, onMounted } from 'vue';
  import MenuItem from './menuItem.vue';
  import { useRoute } from 'vue-router';

  export default {
    props: ['menuList'],
    components: {
      MenuItem,
    },

    setup(props, context) {
      const route = useRoute();
      const internalInstance = getCurrentInstance();
      const gvm = internalInstance.appContext.config.globalProperties;
      const rh = internalInstance.appContext.config.globalProperties.rh;

      const getMenuList = (menuList) => {
        if (!menuList) return [];
        return menuList.map((m) => {
          if (m.children) {
            m.children = m.children.filter((n) => !n.meta.hidden);
            if (m.children.length == 0) {
              m.children = undefined;
            } else {
              getMenuList(m.children);
            }
          }

          return m;
        });
      };
      const state = reactive({
        selectedKeys: [],
        openKeys: [],
        menuList: getMenuList(props.menuList),
        collapsed: false,
      });

      watch(
        () => props.menuList,
        (val, oldVal) => {
          state.menuList = getMenuList(val);
        }
      );

      watch(
        () => gvm.$route,
        (val) => {
          // state.selectedKeys = [val.path];
          const openKeys = rh.breads.slice(0, rh.breads.length - 1);
          state.openKeys = openKeys.map((item) => item.path);

          const parents = rh.breads.filter((m) => !m.meta.hidden);
          state.selectedKeys = parents.slice(-1).map((item) => item.path);
        }
      );

      const toggleCollapsed = () => {
        state.collapsed = !state.collapsed;
        state.openKeys = state.collapsed ? [] : state.openKeys;
      };

      return {
        ...toRefs(state),
        toggleCollapsed,
      };
    },
  };
</script>
